
package com.cool.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * @author bian
 * @date 2021-05-09
 */
@Aspect
@Slf4j
@Component
@EnableAspectJAutoProxy
public class TimeConsumeAspect {
    @Pointcut("execution(* com.cool.service.*.*(..))")
    private void logMethodTimeAll() {}

    @Pointcut("@annotation(com.cool.util.LogRunTime)")
    private void logMethodTimeByAnnotation() {}

    @Pointcut("@within(com.cool.util.LogRunTime)")
    private void logClassMethodTimeByAnnotation() {}

    @Around("logMethodTimeAll()")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object object = pjp.proceed();
        long end = System.currentTimeMillis();
        long costTime = end - start;
        log.info("Run the method: {}, take time: {} ms", pjp.getSignature().getName(), costTime);
        return object;
    }
}
